from fastapi import APIRouter, Depends, Query
from sqlalchemy.orm import Session
from typing import Dict, List, Any, Optional

from app.db.database import get_db
from app.core.security import get_current_user, get_current_active_user
from app.crud import stats as stats_crud

router = APIRouter()


@router.get("/counts", response_model=Dict[str, int])
async def read_counts(
    db: Session = Depends(get_db)
):
    """获取基本计数统计"""
    return stats_crud.get_counts(db)


@router.get("/user-trend", response_model=List[Dict[str, Any]])
async def read_user_trend(
    days: int = Query(30, ge=1, le=365),
    current_user: dict = Depends(get_current_active_user),
    db: Session = Depends(get_db)
):
    """获取用户注册趋势"""
    # 检查是否是管理员
    if current_user.get("role") != "admin":
        days = min(days, 30)  # 非管理员只能查看最近30天的数据
    
    return stats_crud.get_user_trend(db, days=days)


@router.get("/post-trend", response_model=List[Dict[str, Any]])
async def read_post_trend(
    days: int = Query(30, ge=1, le=365),
    current_user: dict = Depends(get_current_active_user),
    db: Session = Depends(get_db)
):
    """获取帖子发布趋势"""
    # 检查是否是管理员
    if current_user.get("role") != "admin":
        days = min(days, 30)  # 非管理员只能查看最近30天的数据
    
    return stats_crud.get_post_trend(db, days=days)


@router.get("/active-users", response_model=List[Dict[str, Any]])
async def read_active_users(
    days: int = Query(7, ge=1, le=30),
    limit: int = Query(10, ge=1, le=100),
    db: Session = Depends(get_db)
):
    """获取活跃用户列表"""
    return stats_crud.get_active_users(db, days=days, limit=limit)


@router.get("/popular-campsites", response_model=List[Dict[str, Any]])
async def read_popular_campsites(
    limit: int = Query(10, ge=1, le=100),
    db: Session = Depends(get_db)
):
    """获取热门营地列表"""
    return stats_crud.get_popular_campsites(db, limit=limit)


@router.get("/dashboard", response_model=Dict[str, Any])
async def read_dashboard(
    current_user: dict = Depends(get_current_active_user),
    db: Session = Depends(get_db)
):
    """获取仪表盘数据（管理后台首页使用）"""
    # 检查是否是管理员
    if current_user.get("role") != "admin":
        days = 30
    else:
        days = 90
    
    # 获取统计数据
    counts = stats_crud.get_counts(db)
    user_trend = stats_crud.get_user_trend(db, days=days)
    post_trend = stats_crud.get_post_trend(db, days=days)
    active_users = stats_crud.get_active_users(db, days=7, limit=10)
    popular_campsites = stats_crud.get_popular_campsites(db, limit=10)
    
    # 组合数据
    return {
        "counts": counts,
        "user_trend": user_trend,
        "post_trend": post_trend,
        "active_users": active_users,
        "popular_campsites": popular_campsites
    } 